<template>
  <div class="chat-window">
    <!-- 聊天头部 -->
    <div class="chat-header" v-if="currentChat">
      <div class="chat-partner-info">
        <el-avatar :size="40" :src="getChatAvatar(currentChat)" />
        <div class="partner-details">
          <h3 class="partner-name">{{ getChatName(currentChat) }}</h3>
          <span class="partner-status" :class="getStatusClass(currentChat)">
            {{ getStatusText(currentChat) }}
          </span>
        </div>
      </div>
      
      <div class="chat-actions">
        <el-button type="text" @click="showChatInfo">
          <el-icon><InfoFilled /></el-icon>
        </el-button>
        <el-button type="text" @click="clearChat">
          <el-icon><Delete /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-chat">
      <div class="empty-content">
        <el-icon size="64" color="#9ca3af"><ChatDotRound /></el-icon>
        <h3>选择聊天开始对话</h3>
        <p>从左侧列表选择一个聊天或发起新的对话</p>
      </div>
    </div>

    <!-- 消息区域 -->
    <div v-if="currentChat" class="messages-container">
      <div class="messages-list" ref="messagesList">
        <!-- 加载更多 -->
        <div v-if="hasMoreMessages" class="load-more">
          <el-button type="text" @click="loadMoreMessages" :loading="loadingMessages">
            加载更多消息
          </el-button>
        </div>

        <!-- 消息列表 -->
        <div
          v-for="message in currentChat.messages"
          :key="message.id"
          class="message-item"
          :class="{
            'own-message': message.senderId === currentUser.id,
            'other-message': message.senderId !== currentUser.id
          }"
        >
          <div class="message-avatar">
            <el-avatar :size="32" :src="getMessageAvatar(message)" />
          </div>
          
          <div class="message-content">
            <div class="message-bubble" :class="getMessageBubbleClass(message)">
              <!-- 文本消息 -->
              <div v-if="message.type === 'text'" class="text-message">
                {{ message.content }}
              </div>
              
              <!-- 图片消息 -->
              <div v-else-if="message.type === 'image'" class="image-message">
                <img 
                  :src="message.content" 
                  alt="图片消息" 
                  @click="previewImage(message.content)"
                />
              </div>
              
              <!-- 文件消息 -->
              <div v-else-if="message.type === 'file'" class="file-message">
                <el-icon><Document /></el-icon>
                <div class="file-info">
                  <span class="file-name">{{ message.fileName }}</span>
                  <span class="file-size">{{ formatFileSize(message.fileSize) }}</span>
                </div>
                <el-button type="text" @click="downloadFile(message)">
                  下载
                </el-button>
              </div>
              
              <div class="message-time">
                {{ formatMessageTime(message.timestamp) }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="message-input-area">
        <!-- 工具栏 -->
        <div class="input-toolbar">
          <el-button type="text" @click="toggleEmoji">
            <el-icon><Star /></el-icon>
          </el-button>
          <el-button type="text" @click="openFilePicker">
            <el-icon><FolderOpened /></el-icon>
          </el-button>
          <el-button type="text" @click="openImagePicker">
            <el-icon><Picture /></el-icon>
          </el-button>
        </div>

        <!-- 文本输入 -->
        <div class="text-input-container">
          <el-input
            v-model="newMessage"
            type="textarea"
            :rows="3"
            placeholder="输入消息..."
            resize="none"
            @keydown="handleKeyDown"
            maxlength="1000"
            show-word-limit
          />
        </div>

        <!-- 发送按钮 -->
        <div class="send-button">
          <el-button 
            type="primary" 
            @click="sendMessage"
            :disabled="!newMessage.trim()"
            :loading="sending"
          >
            <el-icon><Promotion /></el-icon>
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 表情选择器 -->
    <el-dialog
      v-model="showEmojiPicker"
      title="选择表情"
      width="400px"
      align-center
    >
      <div class="emoji-picker">
        <div
          v-for="emoji in emojis"
          :key="emoji"
          class="emoji-item"
          @click="insertEmoji(emoji)"
        >
          {{ emoji }}
        </div>
      </div>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog
      v-model="showImagePreview"
      title="图片预览"
      width="600px"
      align-center
    >
      <div class="image-preview">
        <img :src="previewImageUrl" alt="预览图片" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, watch } from 'vue'

const props = defineProps({
  currentChat: {
    type: Object,
    default: null
  },
  currentUser: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['send-message', 'clear-chat', 'new-chat'])

const newMessage = ref('')
const sending = ref(false)
const showEmojiPicker = ref(false)
const showImagePreview = ref(false)
const previewImageUrl = ref('')
const messagesList = ref(null)
const loadingMessages = ref(false)
const hasMoreMessages = ref(true)

// 表情列表
const emojis = ref(['😀', '😂', '🥰', '😎', '🤔', '👍', '❤️', '🔥', '✨', '🎉'])

// 获取聊天头像
const getChatAvatar = (chat) => {
  if (chat.type === 'private') {
    return chat.participant.avatar
  }
  return chat.groupAvatar || ''
}

// 获取聊天名称
const getChatName = (chat) => {
  if (chat.type === 'private') {
    return chat.participant.name
  }
  return chat.groupName || '群聊'
}

// 获取状态类名
const getStatusClass = (chat) => {
  if (chat.type === 'private') {
    return chat.participant.online ? 'online' : 'offline'
  }
  return 'group'
}

// 获取状态文本
const getStatusText = (chat) => {
  if (chat.type === 'private') {
    return chat.participant.online ? '在线' : '离线'
  }
  return `${chat.memberCount} 名成员`
}

// 获取消息头像
const getMessageAvatar = (message) => {
  return message.senderAvatar || ''
}

// 获取消息气泡类名
const getMessageBubbleClass = (message) => {
  const baseClass = message.senderId === props.currentUser.id ? 'own-bubble' : 'other-bubble'
  return `${baseClass} ${message.type}-bubble`
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B'
  
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

// 格式化消息时间
const formatMessageTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim()) return
  
  sending.value = true
  
  const messageData = {
    id: Date.now(),
    type: 'text',
    content: newMessage.value.trim(),
    senderId: props.currentUser.id,
    senderName: props.currentUser.name,
    senderAvatar: props.currentUser.avatar,
    timestamp: new Date().toISOString(),
    status: 'sending'
  }
  
  try {
    await emit('send-message', messageData)
    newMessage.value = ''
    scrollToBottom()
  } catch (error) {
    console.error('发送消息失败:', error)
  } finally {
    sending.value = false
  }
}

// 处理键盘事件
const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesList.value) {
      messagesList.value.scrollTop = messagesList.value.scrollHeight
    }
  })
}

// 切换表情选择器
const toggleEmoji = () => {
  showEmojiPicker.value = !showEmojiPicker.value
}

// 插入表情
const insertEmoji = (emoji) => {
  newMessage.value += emoji
  showEmojiPicker.value = false
}

// 预览图片
const previewImage = (imageUrl) => {
  previewImageUrl.value = imageUrl
  showImagePreview.value = true
}

// 打开文件选择器
const openFilePicker = () => {
  // 实现文件选择逻辑
  console.log('打开文件选择器')
}

// 打开图片选择器
const openImagePicker = () => {
  // 实现图片选择逻辑
  console.log('打开图片选择器')
}

// 下载文件
const downloadFile = (message) => {
  // 实现文件下载逻辑
  console.log('下载文件:', message)
}

// 显示聊天信息
const showChatInfo = () => {
  // 实现显示聊天信息逻辑
  console.log('显示聊天信息')
}

// 清空聊天
const clearChat = () => {
  emit('clear-chat', props.currentChat.id)
}

// 加载更多消息
const loadMoreMessages = async () => {
  loadingMessages.value = true
  // 实现加载更多消息逻辑
  setTimeout(() => {
    loadingMessages.value = false
    hasMoreMessages.value = false // 模拟没有更多消息
  }, 1000)
}

// 监听当前聊天变化，自动滚动到底部
watch(() => props.currentChat, () => {
  if (props.currentChat) {
    nextTick(() => {
      scrollToBottom()
    })
  }
}, { deep: true })
</script>

<style scoped>
.chat-window {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.chat-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
}

.chat-partner-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.partner-details {
  display: flex;
  flex-direction: column;
}

.partner-name {
  margin: 0;
  font-size: 1rem;
  color: #1f2937;
}

.partner-status {
  font-size: 0.75rem;
  color: #6b7280;
}

.partner-status.online {
  color: #10b981;
}

.partner-status.offline {
  color: #9ca3af;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

.empty-chat {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8fafc;
}

.empty-content {
  text-align: center;
  color: #6b7280;
}

.empty-content h3 {
  margin: 16px 0 8px;
  color: #374151;
}

.messages-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.messages-list {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.load-more {
  text-align: center;
  padding: 16px;
}

.message-item {
  display: flex;
  gap: 12px;
}

.message-item.own-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.own-message .message-content {
  align-items: flex-end;
}

.other-message .message-content {
  align-items: flex-start;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  word-wrap: break-word;
}

.own-bubble {
  background: #4caf50;
  color: white;
  border-bottom-right-radius: 4px;
}

.other-bubble {
  background: #f3f4f6;
  color: #374151;
  border-bottom-left-radius: 4px;
}

.image-bubble {
  padding: 8px;
}

.file-bubble {
  padding: 16px;
}

.text-message {
  line-height: 1.4;
}

.image-message img {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
  cursor: pointer;
  transition: transform 0.2s;
}

.image-message img:hover {
  transform: scale(1.05);
}

.file-message {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.file-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.file-size {
  font-size: 0.75rem;
  color: #6b7280;
}

.own-bubble .file-size {
  color: rgba(255, 255, 255, 0.8);
}

.message-time {
  font-size: 0.75rem;
  margin-top: 4px;
  opacity: 0.7;
}

.message-input-area {
  border-top: 1px solid #e5e7eb;
  padding: 16px 20px;
  background: white;
}

.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.text-input-container {
  margin-bottom: 12px;
}

.send-button {
  display: flex;
  justify-content: flex-end;
}

.emoji-picker {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.emoji-item {
  font-size: 1.5rem;
  text-align: center;
  padding: 8px;
  cursor: pointer;
  border-radius: 8px;
  transition: background-color 0.2s;
}

.emoji-item:hover {
  background-color: #f3f4f6;
}

.image-preview {
  text-align: center;
}

.image-preview img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 8px;
}
</style>